package com.along.study.proxy;

import com.along.study.Config.ProxyConstant;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class VisitorPreHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private ChannelHandlerContext ctx;
    private ByteBuf buf;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf buf) throws Exception {
        this.ctx = ctx;
        Channel channel = ctx.channel();
        byte[] data = new byte[buf.readableBytes()];
        buf.readBytes(data);
        String str = new String(data);
        String[] arr = str.split("\r\n");
        for(String item:arr){
            if(item.startsWith(ProxyConstant.REMOTE_CLIENT)){
                String clientCode = item.split(":")[1].trim();
                channel.attr(ProxyConstant.CLIENT_CODE).set(clientCode);
                break;
            }
        }
       this.buf = Unpooled.wrappedBuffer(data);
        super.channelActive(ctx);
    }

    public void doNextHandlerRead(){
        ctx.fireChannelRead(buf);
    }
}
